package com.zHan.controller;

import com.zHan.anno.Log;
import com.zHan.pojo.Dept;
import com.zHan.pojo.DeptLog;
import com.zHan.pojo.Result;
import com.zHan.service.DeptLogService;
import com.zHan.service.DeptService;
import com.zHan.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 部门管理Controller
 */
@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private EmpService empService;

    @Autowired
    private DeptLogService deptLogService;

    /**
     * 部门列表查询
     *
     * @return
     */
    @GetMapping
    public Result depts() {
        List<Dept> deptList = deptService.list();
        return Result.success(deptList);
    }

    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    @Log
    @Transactional(rollbackFor = Exception.class)  //开启事务管理
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        try {
            boolean flag = deptService.deleteById(id);
            if (flag) {
                //同时删除关联的员工表
                empService.deleteByDeptId(id);
//                throw new Exception("错误");
                return Result.success();
            }
            return Result.error("删除部门失败");
        } finally {
            //不论成功与否，都要记录日志
            DeptLog deptLog=new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，此时解散的是"+id+"号部门");
            deptLogService.insert(deptLog);
        }
    }

    /**
     * 新增部门
     *
     * @param dept
     * @return
     */
    @Log
    @PostMapping
    public Result add(@RequestBody Dept dept) {
        if (deptService.save(dept)) {
            return Result.success();
        }
        return Result.error("新增部门失败");
    }

    /**
     * 根据id查询部门
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    /**
     * 修改部门
     *
     * @param dept
     * @return
     */
    @Log
    @PutMapping
    public Result update(@RequestBody Dept dept) {
        if (deptService.update(dept)) {
            return Result.success();
        }
        return Result.error("修改部门失败");
    }
}
